package com.base.mine;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.BaseApp;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.bean.User;
import com.base.commonlib.recy.BasicRecyViewHolder;
import com.base.commonlib.recy.HFGridMultiTypeGapDecoration;
import com.base.commonlib.recy.HFMultiTypeRecyAdapter;
import com.base.commonlib.recy.animation.ScaleInAnimation;
import com.base.commonlib.sp.SpUtil;
import com.base.commonlib.utils.GlideUtil;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.ToastUtil;
import com.base.commonlib.widget.CommonDialog;
import com.base.home.bean.Score;
import com.base.mine.adapter.HFGridMuiltType;
import com.base.mine.bean.MineData;
import com.base.mine.bean.ScopeBean;
import com.base.mine.databinding.ActivityMineBinding;
import com.base.mine.presenter.MineJPresenter;
import com.base.mine.utils.StatEntity;
import com.base.mine.view.MineJView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by weikailiang on 2020/3/24.
 */
@Route(path = "/mine/mineact")
public class MineActivity extends CBaseBarMvpActivity<MineJPresenter> implements MineJView {
    private ActivityMineBinding mBinding;
    private HFMultiTypeRecyAdapter mAdapter;
    private Disposable disposable;
    @Autowired
    String cover;

    int position = 0;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_mine;
    }

    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityMineBinding) mRootBinding;
        mPresenter = new MineJPresenter(this, this);
        mPresenter.start();
        mBinding.bar.setNavigationIcon(com.base.commonlib.R.drawable.ic_title_back);
        mBinding.bar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //mBinding.cover.setText(cover);
        mBinding.imgRight.setVisibility(View.VISIBLE);
        mBinding.imgRight.setImageResource(R.mipmap.ic_setting);
        mBinding.imgRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/mine/setter")
                        .withString("userId", mPresenter.mUser.getUserId())
                        .withString("account", mPresenter.mUser.getPhone())
                        .navigation();
            }
        });
        setBarTitle("我的");
        if (mPresenter.mUser != null) {
            if (!TextUtils.isEmpty(mPresenter.mUser.getUserName())) {
                mBinding.ivName.setText(mPresenter.mUser.getUserName());
            } else {
                mBinding.ivName.setText("");
            }
            if (!TextUtils.isEmpty(mPresenter.mUser.getOrgName())) {
                if (mPresenter.mUser.getOrgName().equals(mPresenter.mUser.getDeptName())) {
                    mBinding.ivDept.setText(mPresenter.mUser.getOrgName());
                } else {
                    mBinding.ivDept.setText(mPresenter.mUser.getOrgName() + "-" + mPresenter.mUser.getDeptName());
                }
            }else {
                if (!TextUtils.isEmpty(mPresenter.mUser.getDeptName())){
                    mBinding.ivDept.setText(mPresenter.mUser.getDeptName());
                }
            }
            //if (!TextUtils.isEmpty(mPresenter.mUser.getAvatar())) {
            RequestOptions requestOptions = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .placeholder(R.mipmap.ic_default_img)
                    .error(R.mipmap.ic_default_img)
                    .centerCrop();
            Glide.with(mContext).load(mPresenter.mUser.getAvatar()).apply(requestOptions).into(mBinding.ivAvatar);
               // GlideUtil.load(mContext, mPresenter.mUser.getAvatar(), mBinding.ivAvatar);
            //}
        }

        mBinding.llCenper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/mine/accountprivacy").navigation();
            }
        });

        Disposable disposable = RxBus2.getInstance().doSubscribe(User.class, new Consumer<User>() {
            @Override
            public void accept(User user) throws Exception {
                if (!TextUtils.isEmpty(user.getAvatar())) {
                    GlideUtil.load(mContext, user.getAvatar(), mBinding.ivAvatar);
                }
            }
        });

        mBinding.btLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonDialog commonDialog = new CommonDialog(mContext, "确定要退出登录?");
                commonDialog.setOnPosClick(new CommonDialog.OnPosClick() {
                    @Override
                    public void onClick() {
//                        SpUtil.setToken("");
//                        ARouter.getInstance().build(RouteConfig.ACTIVITIY_LOGIN).navigation();
//
                        mPresenter.loginOut(mPresenter.mUser.getUserId());
                    }
                });
                commonDialog.show();
            }
        });

        RxBus2.getInstance().addSubscription(this, disposable);


    }

    @Override
    protected void start() {
        mPresenter.getScope("edu");
        if (mAdapter == null) {
            mAdapter = new HFMultiTypeRecyAdapter();
            mAdapter.openLoadAnimation(new ScaleInAnimation());
            mBinding.recycler.setAdapter(mAdapter);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 12);
            HFGridMuiltType spanSizeLookup = new HFGridMuiltType();
            spanSizeLookup.setAdapter(mAdapter);
            spanSizeLookup.setLayoutManager(gridLayoutManager);
            gridLayoutManager.setSpanSizeLookup(spanSizeLookup);
            mBinding.recycler.setLayoutManager(gridLayoutManager);
            HFGridMultiTypeGapDecoration gapDecoration = new HFGridMultiTypeGapDecoration(0);
            gapDecoration.setOffsetTopEnabled(false);
            mBinding.recycler.addItemDecoration(gapDecoration);
        }
        mAdapter.refreshDatas(MineData.getWorkFragmentDatas());

        disposable = RxBus2.getInstance().doSubscribe(StatEntity.class, new Consumer<StatEntity>() {
            @Override
            public void accept(StatEntity bean) throws Exception {
                if (bean.getState() == 0x2110) {



                    final String[] item = {"手机：18550095568", "座机：0512-88998164"};
                    final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);//得到构造器
                    builder.setTitle("请选择");
                    builder.setItems(item, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (which == 0){
                                position= 0;
                                call("tel:"+"18550095568");
                            }else if (which == 1){
                                position=1;
                                call("tel:"+"0512-88998164");
                            }
                        }
                    });
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();



//                    CommonDialog dialog = new CommonDialog(mContext, "\t\t您确定需要技术服务吗？\n\t\t拨打电话：010-10000", "提示", "取消", "确定");
//                    dialog.setOnPosClick(new CommonDialog.OnPosClick() {
//                        @Override
//                        public void onClick() {
//                            call("tel:"+"10000");
//
//                        }
//                    });
//                    dialog.show();
                }
            }
        });

    }



    public static final int REQUEST_CALL_PERMISSION = 10111; //拨号请求码

    /**
     * 判断是否有某项权限
     * @param string_permission 权限
     * @param request_code 请求码
     * @return
     */
    public boolean checkReadPermission(String string_permission,int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(this, string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(this, new String[]{string_permission}, request_code);
        }
        return flag;
    }

    /**
     * 检查权限后的回调
     * @param requestCode 请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CALL_PERMISSION: //拨打电话
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(this,"请允许拨号权限后再试",Toast.LENGTH_SHORT).show();
                } else {//成功
                    if (position == 0){
                        call("tel:"+"18550095568");
                    }else if (position == 1){
                        call("tel:"+"0512-88998164");
                    }

                }
                break;
        }
    }

    /**
     * 拨打电话（直接拨打）
     * @param telPhone 电话
     */
    public void call(String telPhone){
        if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_CALL_PERMISSION)){
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(telPhone));
            startActivity(intent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }

    }

    @Override
    public void returnScope(ScopeBean scopeBean) {
        mBinding.cover.setText(scopeBean.getRealAllScore()+"");
    }

    @Override
    public void returnLoginOut(String msg) {
        //ToastUtil.show("退出成功");
        SpUtil.setToken("");
        ARouter.getInstance().build("/mine/pwdlogin").navigation();
        BaseApp.clearActivity();
    }
}
